package cj.web.uc.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;
import cj.web.constants.AccessTrackEnum;
import cj.web.yc.utils.MD5Security;

/**
 * 拦截器
 * @author Administrator
 *
 */
public class AccessTrackInterceptor extends ControllerInterceptorAdapter {
	
	public final static String KEY_TOKEN_ = "6a04f2d6b4774052b1298903d4171730"; 
	
    public AccessTrackInterceptor() {
        setPriority(29600);
    }

//    @Override
//    public Class<? extends Annotation> getRequiredAnnotationClass() {
//    	System.out.println("1111");
//        return PriCheckRequired.class; // 这是一个注解，只有标过的controller才会接受这个拦截器的洗礼。
//    }

    @Override
    public Object before(Invocation inv) throws Exception {
    	//---------------cookie中获取参数，转换成Map
    	Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
    	Cookie[] cookies = inv.getRequest().getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
    	//---------------查看cookie中有没有索要字段
        if(cookieMap.containsKey("phone") && cookieMap.containsKey("memberId") && cookieMap.containsKey("_token_")){
        	
        	//帐号
        	String phone = cookieMap.get("phone").getValue();
        	//帐号Id
        	String memberId = cookieMap.get("memberId").getValue();
        	//cookie中的Key
        	String _token_ = cookieMap.get("_token_").getValue();
        	
        	//取出加密后的Key
        	String token = MD5Security.returnSingKey(phone+memberId+KEY_TOKEN_);
        	
        	if(!_token_.equals(token)){
        		//不存在
            	StringBuffer strParameters = new StringBuffer();
    			Map map = inv.getRequest().getParameterMap();
    			Set keSet = map.entrySet();
    			for (Iterator itr = keSet.iterator(); itr.hasNext();) {
    				Map.Entry me = (Map.Entry) itr.next();
    				Object ok = me.getKey();
    				Object ov = me.getValue();
    				String[] value = new String[1];
    				if (ov instanceof String[]) {
    					value = (String[]) ov;
    				} else {
    					value[0] = ov.toString();
    				}
    				for (int k = 0; k < value.length; k++) {
    					if(strParameters.length()>0){
    						strParameters.append("&"+ok + "=" + value[k]);
    					}else{
    						strParameters.append(ok + "=" + value[k]);
    					}
    				}
    			}
//    			System.out.println(inv.getRequestPath().getControllerPath()+
//    					inv.getRequestPath().getActionPath()+"?"+strParameters);
    			String returnPage = "";
    			if(strParameters.length()>0){
    				returnPage = inv.getRequestPath().getControllerPath()+inv.getRequestPath().getActionPath()+"?"+strParameters;
    			}else{
    				returnPage = inv.getRequestPath().getControllerPath()+inv.getRequestPath().getActionPath();
    			}
    			
    	        Cookie cookie = new Cookie("returnPage", returnPage);
    	        cookie.setPath("/");
    	        cookie.setMaxAge( 622080000 );
    	        inv.getResponse().addCookie(cookie);
    			
            	inv.getResponse().sendRedirect(inv.getRequestPath().getCtxpath()+"/user/loginPage");
                return Boolean.FALSE;
            }
        	
        	//存在
        	boolean flag = AccessTrackEnum.reMethodExist(inv.getMethod().getName());
//        	System.out.println(inv.getRequestPath().getControllerPath()+"==="+inv.getRequestPath().getActionPath());
            return Boolean.TRUE;
        }else{
        	//不存在
        	StringBuffer strParameters = new StringBuffer();
			Map map = inv.getRequest().getParameterMap();
			Set keSet = map.entrySet();
			for (Iterator itr = keSet.iterator(); itr.hasNext();) {
				Map.Entry me = (Map.Entry) itr.next();
				Object ok = me.getKey();
				Object ov = me.getValue();
				String[] value = new String[1];
				if (ov instanceof String[]) {
					value = (String[]) ov;
				} else {
					value[0] = ov.toString();
				}
				for (int k = 0; k < value.length; k++) {
					if(strParameters.length()>0){
						strParameters.append("&"+ok + "=" + value[k]);
					}else{
						strParameters.append(ok + "=" + value[k]);
					}
				}
			}
//			System.out.println(inv.getRequestPath().getControllerPath()+
//					inv.getRequestPath().getActionPath()+"?"+strParameters);
			String returnPage = "";
			if(strParameters.length()>0){
				returnPage = inv.getRequestPath().getControllerPath()+inv.getRequestPath().getActionPath()+"?"+strParameters;
			}else{
				returnPage = inv.getRequestPath().getControllerPath()+inv.getRequestPath().getActionPath();
			}
			
	        Cookie cookie = new Cookie("returnPage", returnPage);
	        cookie.setPath("/");
	        cookie.setMaxAge( 622080000 );
	        inv.getResponse().addCookie(cookie);
			
        	inv.getResponse().sendRedirect(inv.getRequestPath().getCtxpath()+"/user/loginPage");
            return Boolean.FALSE;
        } 
    }
    
    @Override
    public void afterCompletion(final Invocation inv, Throwable ex) throws Exception {
//    	System.out.println("-----");
    }
}